import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '.'
import { useMenuListStore, useTokenStore } from '@/stores/counter'
import { dynamicMenuRoutes } from '@/router/constructRouter'
import { nextTick} from 'vue'
import type { MenuTypes } from '@/resources/interface/menu/MenuTypes.ts'

export const mainRouter: MenuTypes[] = [
  {
    no: '0',
    router: '/',
    name: '工作台',
    component: '/MainView',
    icon: '',
    type: 0,
    children: [],
  },
]

NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 1000, // 递增进度条的速度
  showSpinner: true, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  const tokenStore = useTokenStore()
  if (to.path === '/login') {
    next()
    return
  }
  if (tokenStore.hasToken()) {
    next()
  } else {
    //校验是否存在路由
    next('/login')
  }
})

router.afterEach(() => {
  NProgress.done()
})

router.isReady().then(async () => {
  const tokenStore = useTokenStore()
  if (tokenStore.hasToken()) {
    const listStore = useMenuListStore()
    const list: MenuTypes[] = listStore.menuList || []
    if (mainRouter[0].children) {
      const children = mainRouter[0].children
      // 遍历并将不重复的子菜单项加入
      list.forEach((child) => {
        if (!children.some((item: MenuTypes) => item.name === child.name)) {
          children.push(child)
        }
      })
      mainRouter[0].children = children
    }
    const menuList = dynamicMenuRoutes(mainRouter)
    for (const menuRoute of menuList) {
      router.addRoute(menuRoute)
    }
    // 等待下一次 DOM 更新循环，确保所有路由都已添加
    await nextTick()
    await router.replace(router.currentRoute.value.fullPath)
  } else {
    await router.push('/login')
  }
})
